import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import React, { useState, useEffect } from 'react'

// 界面组件
import { View, Image, ScrollView } from '@tarojs/components'

// 界面布局
import { CTopBar, CSkeleton } from '@/components'
import HomeSearch from './HomeSearch'
import HomeBanner from './HomeBanner/index'

// 请求数据

import GetTopBarInfo from '@/utils/GetTopBarInfo'
import CMore from '../../components/CMore'
import CCard from '../../components/CCard'
import { GetHomeBannerArr, GetHomeCardData, get_user_id_api } from './service'
import './index.scss'
import './AtSearchBar.scss'
import curtainPng from '@/assets/curtain.png'
import { get_user_info, login_by_auto } from '@/pages/My/service'
import { AtButton, AtCurtain } from 'taro-ui'
/**
 * 首页界面
 * @returns {JSX.Element}
 */
interface IQuestions {
  layoutId: number
  price: number
  questionId: number
  questionImg: string
  questionName: string
  questionNumber: number
  questionSubtitle: string
  testNumber: number
}
interface IHomeCardData {
  id: number
  layoutEnglish: string
  layoutSubtitle: string
  layoutTitle: string
  questions: IQuestions[]
}
function HomePage(): JSX.Element {
  const p = Taro.useRouter().params
  console.log(p)

  const [loading, setLoading] = useState(false)
  const [BannerArr, setBannerArr] = useState([])
  const [HomeCardData, setHomeCardData] = useState<IHomeCardData[]>([])
  const [references, setreferences] = useState<any>(p.references ? parseInt(p.references) : 0) //  分享人的id
  const [id, setId] = useState<any>(0) //  本人的id
  const [Curtain, setCurtain] = useState(false) //  帘幕开关

  useEffect(() => {
    getUserInfo()
  }, [])

  usePullDownRefresh(() => {
    get_home_data()
  })

  // 根据 推荐人的用户id 决定是否渲染
  useEffect(() => {
    if (!references) return
    setCurtain(true)
  }, [references])

  const get_home_data = async () => {
    // 首页数据请求
    await GetHomeCardData().then(({ result, data }) => {
      if (result < 0) return
      const { list = [] } = data
      setHomeCardData(list)
      Taro.stopPullDownRefresh()
    })
  }

  // 请求该用户id
  function get_user_id() {
    get_user_id_api().then(({ result, data }) => {
      setId(Number(data))
    })
  }

  // 轮播图跳转
  function gotoHomeCardDetails(id, title) {
    Taro.navigateTo({
      url: '/pages/Home/HomeCardDetails/index?id=' + id + '&title=' + title,
    })
  }

  // 获取微信code 并且登录
  function getSysInfo() {
    const sysinfo = Taro.getSystemInfoSync()
    Taro.setStorageSync('system', sysinfo.system)
  }
  function getUserInfo() {
    Taro.login({
      success: function (res) {
        if (res.code) {
          // 登录传入 推荐人id
          login_by_auto(res.code, references).then(({ result, data, token }) => {
            if (result === 1999) {
              Taro.setStorage({
                key: 'authorization',
                data: token,
                success: (res) => {
                  console.log('存储token成功', res)
                  GetUserInfo()
                },
                fail: (err) => {
                  console.log('存储token失败', err)
                },
              })
            } else {
              console.log('获取token失败')
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
    })
  }

  // 登录成功请求用户信息并存储  然后请求其他数据
  function GetUserInfo() {
    get_user_info().then((infoObj) => {
      get_user_id()
      getSysInfo()
      get_home_data()
      getBanner()
      Taro.setStorage({
        key: 'user_info',
        data: infoObj.data,
      })
    })
  }
  // 获取轮播图
  function getBanner() {
    GetHomeBannerArr().then(({ result, data }) => setBannerArr(data))
  }

  // 关闭帘幕
  function onCurtainClose() {
    setCurtain(false)
  }

  // 分享给好友
  useShareAppMessage((res) => {
    console.log(Taro.getCurrentPages())
    console.log(res)
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '悦心理测评',
      path: `/pages/Home/index?references=${id}`,
      imageUrl: '../../assets/home_logo.png',
    }
  })
  // 分享到朋友圈
  useShareTimeline(() => {
    console.log('onShareTimeline')
    return {
      title: '悦心理测评',
      path: `/pages/Home/index?references${id}`,
      imageUrl: '../../assets/home_logo.png',
    }
  })

  // 自定义颜色
  const colorArr = ['#E93C00', '#1D2085', '#F9BE25', '#FF9100']
  return (
    <View className='home' style={{ paddingTop: `${GetTopBarInfo().TopBarHeight}px` }}>
      <CTopBar title='悦心理测评'></CTopBar>
      <ScrollView scrollY className='content'>
        {/* <HomeLogoDescribe /> */}
        <HomeSearch loading={loading} />
        <HomeBanner loading={loading} bannerArr={BannerArr} />

        {HomeCardData.map((item, index) => {
          return (
            <View key={index} className='item'>
              <CMore name={item.layoutTitle} subTitle={item.layoutSubtitle} enTitle={item.layoutEnglish} color={colorArr[index]} />
              <View className='week'>
                {item.questions.map((c, i) => {
                  return (
                    <View
                      key={i}
                      className='wrapper'
                      onClick={() => {
                        gotoHomeCardDetails(c.questionId, c.questionName)
                      }}
                    >
                      <CCard
                        questionName={c.questionName}
                        questionSubtitle={c.questionSubtitle}
                        price={c.price}
                        testNumber={c.testNumber}
                        questionImg={c.questionImg}
                      ></CCard>
                    </View>
                  )
                })}
              </View>
            </View>
          )
        })}
        <AtCurtain isOpened={Curtain} onClose={onCurtainClose}>
          <Image style='width:100%;height:250px' src={curtainPng} />
        </AtCurtain>
      </ScrollView>
    </View>
  )
}

export default HomePage
